/*
 * scheduler.c
 *
 *  Created on: Feb 25, 2012
 *      Author: Holly
 */
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include "scheduler.h"


int i;
int priority;
int indexNo;
int numberOfProcesses = 4;
process lastProc;
process proc;

process getProcess(process procs[], char policy){
	indexNo = -1;
	/*find the last process run*/
	for (i = 0; i<numberOfProcesses; i++){
		if (procs[i].wasLastProcessRun == 1){
			indexNo = i;
			break;
		}
	} /*if this is the first process to run, choose first in list*/
	if (indexNo == -1)
		proc = procs[0];
	else{
		lastProc = procs[indexNo];
		switch (policy){
		case 'R': /*Round Robin scheduling policy.  If there are no runnable*/
		case 'r': /*processes other than lastProcess, lastProcess will be chosen*/
			proc = procs[(lastProc.id + 1) % numberOfProcesses];
			while (proc.status != RUNNABLE)
				proc = procs[(lastProc.id + 1) % numberOfProcesses];
			break;
		case 'P':  /*priority scheduling, the runnable process with the*/
		case 'p':  /*highest priority other than the last process*/
			priority = 0;
			indexNo = -1;
			for(i = 0; i<numberOfProcesses; i++){
				if (procs[i].wasLastProcessRun != 1 && procs[i].status == RUNNABLE &&
						procs[i].priority > priority){
					priority = procs[i].priority;
					indexNo = i;
				}
			}
			if(indexNo == -1 && lastProc.status == RUNNABLE)
				proc = lastProc;
			else
				proc = procs[indexNo];
			break;

		case 'L':/*lottery scheduling, randomly choose a runnable process*/
		case 'l':
			srand(time(NULL));
			do {
				i = rand() % numberOfProcesses;
				proc = procs[i];
			} while (procs[i].status != RUNNABLE);
			break;
		}
	}
	lastProc.wasLastProcessRun = 0;
	printf("SCHEDULER: running process %d (%s) next.\n",proc.id, proc.strName);
	return proc;
}

void printProcessStates(process procs[]){
	for(i=0; i<numberOfProcesses; i++){
		proc = procs[i];
		printf("  Process %d (%s)'s state: %s\n", proc.id, proc.strName,
				proc.strStatus);
	}
	printf("\n");
}


